// component/card/downposter/downposter.js
const app = getApp();

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        'id1': {type: Number,value: 0},
        'popUp': {type: Boolean, value: false},
        'name': {type: String, value: ''},
        'no': {type: String, value: ''},
    },

    /**
     * 组件的初始数据
     */
    data: {
        popUp: false,
        tips: false,
    },


    lifetimes: {
        attached() {}
    },
    observers: {
        "id1": function (id1) {
            if(id1 != 0){
                this.ecardposter(id1);
            }
        },
    },

    /**
     * 组件的方法列表
     */
    methods: {
        ecardposter: function (id) {
            app.func.getPromise('/distribute/ecardposter/' + id)
                .then(([code, res]) => {
                    this.setData({poster: res.data});
                })
        },


        cancel: function () {
            this.setData({popUp: false, tips: false});
        },

        opencard: function () {
            this.setData({
                popUp: false
            }, () => {
                this.saveToAlbum();
            })
        },

        tips: function () {
            this.setData({tips: true});
        },


        saveToAlbum: function () {
            var that = this;
            return app.func.wxPromise("authorize", {scope: "scope.writePhotosAlbum"})
                .then(() => {
                    app.func.wxPromise('showLoading', {title: '正在下载'})
                    return app.func.wxPromise("downloadFile", {
                        url: this.data.poster
                    });
                }, () => {
                    return app.func.checkPermission("scope.writePhotosAlbum", "相册", that);
                })
                .then((res) => {
                    var path = res.tempFilePath;
                    return app.func.wxPromise("saveImageToPhotosAlbum", {filePath: path})
                        .finally(() => {
                            wx.getFileSystemManager().unlinkSync(path);
                        })
                })
                .then(() => {
                    wx.hideLoading();
                    return app.func.toastPromise("保存成功", "success");
                })
                .catch((e) => {
                    console.log(e);
                    wx.hideLoading();
                });
        },

        setting: function () {
            this.setData({tips: false});
            app.func.wxPromise("openSetting")
                .then((res) => {
                    if (res.authSetting[this.data.scope]) {
                        wx.navigateBack({
                            delta: 1
                        });
                    }
                })
        },

    }
})
